<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Window.name属性详解</title>
    <style>
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            line-height: 1.6;
            margin: 20px;
            background-color: #f5f5f5;
        }
        .container {
            max-width: 1000px;
            margin: 0 auto;
            background: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        h1 {
            color: #333;
            text-align: center;
            border-bottom: 3px solid #007acc;
            padding-bottom: 10px;
        }
        h2 {
            color: #007acc;
            margin-top: 30px;
            border-left: 4px solid #007acc;
            padding-left: 15px;
        }
        .demo-box {
            background: #f8f9fa;
            border: 1px solid #e9ecef;
            border-radius: 8px;
            padding: 20px;
            margin: 15px 0;
        }
        .demo-box h3 {
            color: #495057;
            margin-top: 0;
        }
        .code-block {
            background: #f1f3f4;
            border: 1px solid #e9ecef;
            border-radius: 5px;
            padding: 15px;
            margin: 10px 0;
            overflow-x: auto;
            font-family: 'Consolas', 'Monaco', monospace;
        }
        .result {
            background: #d1ecf1;
            border: 1px solid #bee5eb;
            border-radius: 5px;
            padding: 15px;
            margin: 10px 0;
        }
        .warning {
            background: #fff3cd;
            border: 1px solid #ffeaa7;
            border-radius: 5px;
            padding: 15px;
            margin: 10px 0;
        }
        .info {
            background: #d4edda;
            border: 1px solid #c3e6cb;
            border-radius: 5px;
            padding: 15px;
            margin: 10px 0;
        }
        button {
            background: #007acc;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 5px;
            cursor: pointer;
            margin: 5px;
        }
        button:hover {
            background: #0056b3;
        }
        .highlight {
            background: #fff3cd;
            padding: 2px 4px;
            border-radius: 3px;
        }
        ul, ol {
            padding-left: 20px;
        }
        li {
            margin: 8px 0;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🌐 Window.name属性详解</h1>
        
        <h2>📖 什么是Window.name属性</h2>
        <div class="demo-box">
            <p><strong>Window.name</strong> 是浏览器中每个窗口/框架都拥有的一个特殊属性，它最初是为了给窗口或框架命名而设计的。</p>
            
            <div class="info">
                <h3>💡 关键特性</h3>
                <ul>
                    <li><strong>默认值：</strong>空字符串 <code>""</code></li>
                    <li><strong>数据类型：</strong>字符串</li>
                    <li><strong>作用域：</strong>全局可访问</li>
                    <li><strong>持久性：</strong>在页面导航过程中保持</li>
                </ul>
            </div>
        </div>

        <h2>🔍 基础演示</h2>
        <div class="demo-box">
            <h3>1. 查看默认值</h3>
            <div class="code-block">
                console.log('window.name的默认值:', window.name);
                console.log('typeof window.name:', typeof window.name);
                console.log('window.name === "":', window.name === "");
            </div>
            <button onclick="showDefaultValue()">运行代码</button>
            <div id="default-result" class="result" style="display: none;"></div>
        </div>

        <div class="demo-box">
            <h3>2. 设置和获取name属性</h3>
            <div class="code-block">
                // 设置name属性
                window.name = "我的窗口";
                console.log('设置后的name:', window.name);
                
                // 直接访问（因为name是全局属性）
                name = "新的名称";
                console.log('直接赋值后的name:', name);
            </div>
            <button onclick="showSetValue()">运行代码</button>
            <div id="set-result" class="result" style="display: none;"></div>
        </div>

        <h2>🎯 实际应用场景</h2>
        
        <div class="demo-box">
            <h3>1. 窗口间通信</h3>
            <div class="code-block">
                // 父窗口设置子窗口名称
                const childWindow = window.open('about:blank', 'childWindow');
                childWindow.name = '子窗口标识';
                
                // 子窗口可以通过name识别自己
                console.log('当前窗口名称:', window.name);
            </div>
            <button onclick="showWindowCommunication()">运行代码</button>
            <div id="comm-result" class="result" style="display: none;"></div>
        </div>

        <div class="demo-box">
            <h3>2. 页面状态标记</h3>
            <div class="code-block">
                // 标记页面状态
                window.name = 'user-logged-in';
                
                // 检查用户状态
                if (window.name === 'user-logged-in') {
                    console.log('用户已登录');
                } else {
                    console.log('用户未登录');
                }
            </div>
            <button onclick="showPageState()">运行代码</button>
            <div id="state-result" class="result" style="display: none;"></div>
        </div>

        <div class="demo-box">
            <h3>3. 数据传递（跨页面）</h3>
            <div class="code-block">
                // 页面A：存储数据
                window.name = JSON.stringify({
                    userId: 123,
                    userName: '张三',
                    lastVisit: new Date().toISOString()
                });
                
                // 页面B：读取数据
                try {
                    const userData = JSON.parse(window.name);
                    console.log('用户数据:', userData);
                } catch (e) {
                    console.log('无法解析数据');
                }
            </div>
            <button onclick="showDataTransfer()">运行代码</button>
            <div id="data-result" class="result" style="display: none;"></div>
        </div>

        <h2>⚠️ 注意事项和限制</h2>
        
        <div class="warning">
            <h3>🚨 安全限制</h3>
            <ul>
                <li><strong>同源策略：</strong>只有同源的页面才能访问name属性</li>
                <li><strong>数据大小：</strong>name属性有长度限制（通常2MB左右）</li>
                <li><strong>数据类型：</strong>只能存储字符串，复杂数据需要序列化</li>
                <li><strong>隐私问题：</strong>避免存储敏感信息</li>
            </ul>
        </div>

        <div class="demo-box">
            <h3>长度限制测试</h3>
            <div class="code-block">
                // 测试name属性的长度限制
                const longString = 'a'.repeat(1000000); // 100万个字符
                
                try {
                    window.name = longString;
                    console.log('设置成功，长度:', window.name.length);
                } catch (e) {
                    console.log('设置失败:', e.message);
                }
            </div>
            <button onclick="testLengthLimit()">运行代码</button>
            <div id="length-result" class="result" style="display: none;"></div>
        </div>

        <h2>🆚 与其他存储方式的对比</h2>
        
        <div class="demo-box">
            <h3>存储方式对比表</h3>
            <table style="width: 100%; border-collapse: collapse; margin: 15px 0;">
                <thead>
                    <tr style="background: #f8f9fa;">
                        <th style="border: 1px solid #dee2e6; padding: 10px;">存储方式</th>
                        <th style="border: 1px solid #dee2e6; padding: 10px;">持久性</th>
                        <th style="border: 1px solid #dee2e6; padding: 10px;">作用域</th>
                        <th style="border: 1px solid #dee2e6; padding: 10px;">大小限制</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td style="border: 1px solid #dee2e6; padding: 10px;"><code>window.name</code></td>
                        <td style="border: 1px solid #dee2e6; padding: 10px;">跨页面导航</td>
                        <td style="border: 1px solid #dee2e6; padding: 10px;">窗口级别</td>
                        <td style="border: 1px solid #dee2e6; padding: 10px;">~2MB</td>
                    </tr>
                    <tr>
                        <td style="border: 1px solid #dee2e6; padding: 10px;"><code>localStorage</code></td>
                        <td style="border: 1px solid #dee2e6; padding: 10px;">永久</td>
                        <td style="border: 1px solid #dee2e6; padding: 10px;">域名级别</td>
                        <td style="border: 1px solid #dee2e6; padding: 10px;">~5-10MB</td>
                    </tr>
                    <tr>
                        <td style="border: 1px solid #dee2e6; padding: 10px;"><code>sessionStorage</code></td>
                        <td style="border: 1px solid #dee2e6; padding: 10px;">会话期间</td>
                        <td style="border: 1px solid #dee2e6; padding: 10px;">标签页级别</td>
                        <td style="border: 1px solid #dee2e6; padding: 10px;">~5-10MB</td>
                    </tr>
                    <tr>
                        <td style="border: 1px solid #dee2e6; padding: 10px;"><code>cookie</code></td>
                        <td style="border: 1px solid #dee2e6; padding: 10px;">可设置过期时间</td>
                        <td style="border: 1px solid #dee2e6; padding: 10px;">域名级别</td>
                        <td style="border: 1px solid #dee2e6; padding: 10px;">~4KB</td>
                    </tr>
                </tbody>
            </table>
        </div>

        <h2>🛠️ 实用工具函数</h2>
        
        <div class="demo-box">
            <h3>Name属性管理工具</h3>
            <div class="code-block">
                // 安全的name属性管理工具
                const NameManager = {
                    // 设置数据
                    set: (key, value) => {
                        try {
                            const data = JSON.parse(window.name || '{}');
                            data[key] = value;
                            window.name = JSON.stringify(data);
                            return true;
                        } catch (e) {
                            console.error('设置name属性失败:', e);
                            return false;
                        }
                    },
                    
                    // 获取数据
                    get: (key) => {
                        try {
                            const data = JSON.parse(window.name || '{}');
                            return data[key];
                        } catch (e) {
                            console.error('获取name属性失败:', e);
                            return null;
                        }
                    },
                    
                    // 删除数据
                    remove: (key) => {
                        try {
                            const data = JSON.parse(window.name || '{}');
                            delete data[key];
                            window.name = JSON.stringify(data);
                            return true;
                        } catch (e) {
                            console.error('删除name属性失败:', e);
                            return false;
                        }
                    },
                    
                    // 清空所有数据
                    clear: () => {
                        window.name = '';
                        return true;
                    },
                    
                    // 获取所有数据
                    getAll: () => {
                        try {
                            return JSON.parse(window.name || '{}');
                        } catch (e) {
                            console.error('解析name属性失败:', e);
                            return {};
                        }
                    }
                };
                
                // 使用示例
                NameManager.set('user', { id: 1, name: '张三' });
                NameManager.set('theme', 'dark');
                console.log('用户信息:', NameManager.get('user'));
                console.log('所有数据:', NameManager.getAll());
            </div>
            <button onclick="showNameManager()">运行代码</button>
            <div id="manager-result" class="result" style="display: none;"></div>
        </div>

        <h2>📝 总结</h2>
        <div class="info">
            <h3>Window.name属性的特点</h3>
            <ul>
                <li><strong>历史遗留：</strong>最初用于窗口/框架命名</li>
                <li><strong>全局访问：</strong>可以直接使用 <code>name</code> 而不需要 <code>window.name</code></li>
                <li><strong>跨页面持久：</strong>在页面导航过程中保持数据</li>
                <li><strong>字符串存储：</strong>只能存储字符串，需要序列化复杂数据</li>
                <li><strong>安全限制：</strong>受同源策略保护</li>
                <li><strong>现代替代：</strong>现在更推荐使用 localStorage、sessionStorage 等</li>
            </ul>
        </div>
    </div>

    <script>
        // 演示函数
        function showDefaultValue() {
            const result = document.getElementById('default-result');
            result.innerHTML = `
                <strong>运行结果：</strong><br>
                window.name的默认值: "${window.name}"<br>
                typeof window.name: ${typeof window.name}<br>
                window.name === "": ${window.name === ""}
            `;
            result.style.display = 'block';
        }

        function showSetValue() {
            // 保存原始值
            const originalName = window.name;
            
            // 设置新值
            window.name = "我的窗口";
            const afterSet = window.name;
            
            // 直接赋值
            name = "新的名称";
            const afterDirect = name;
            
            // 恢复原始值
            window.name = originalName;
            
            const result = document.getElementById('set-result');
            result.innerHTML = `
                <strong>运行结果：</strong><br>
                设置后的name: "${afterSet}"<br>
                直接赋值后的name: "${afterDirect}"
            `;
            result.style.display = 'block';
        }

        function showWindowCommunication() {
            const result = document.getElementById('comm-result');
            result.innerHTML = `
                <strong>运行结果：</strong><br>
                当前窗口名称: "${window.name}"<br>
                <em>注意：在实际应用中，子窗口会显示设置的名称</em>
            `;
            result.style.display = 'block';
        }

        function showPageState() {
            const originalName = window.name;
            
            window.name = 'user-logged-in';
            const status = window.name === 'user-logged-in' ? '用户已登录' : '用户未登录';
            
            window.name = originalName;
            
            const result = document.getElementById('state-result');
            result.innerHTML = `
                <strong>运行结果：</strong><br>
                ${status}
            `;
            result.style.display = 'block';
        }

        function showDataTransfer() {
            const originalName = window.name;
            
            // 存储数据
            window.name = JSON.stringify({
                userId: 123,
                userName: '张三',
                lastVisit: new Date().toISOString()
            });
            
            // 读取数据
            let userData;
            try {
                userData = JSON.parse(window.name);
            } catch (e) {
                userData = '无法解析数据';
            }
            
            window.name = originalName;
            
            const result = document.getElementById('data-result');
            result.innerHTML = `
                <strong>运行结果：</strong><br>
                用户数据: ${JSON.stringify(userData, null, 2)}
            `;
            result.style.display = 'block';
        }

        function testLengthLimit() {
            const result = document.getElementById('length-result');
            const longString = 'a'.repeat(100000); // 10万个字符，避免过长
            
            try {
                const originalName = window.name;
                window.name = longString;
                const success = window.name.length === longString.length;
                window.name = originalName;
                
                result.innerHTML = `
                    <strong>运行结果：</strong><br>
                    设置${success ? '成功' : '失败'}，实际长度: ${window.name.length}<br>
                    <em>注意：不同浏览器可能有不同的长度限制</em>
                `;
            } catch (e) {
                result.innerHTML = `
                    <strong>运行结果：</strong><br>
                    设置失败: ${e.message}
                `;
            }
            result.style.display = 'block';
        }

        function showNameManager() {
            const result = document.getElementById('manager-result');
            
            // 保存原始值
            const originalName = window.name;
            
            // 创建管理工具
            const NameManager = {
                set: (key, value) => {
                    try {
                        const data = JSON.parse(window.name || '{}');
                        data[key] = value;
                        window.name = JSON.stringify(data);
                        return true;
                    } catch (e) {
                        console.error('设置name属性失败:', e);
                        return false;
                    }
                },
                get: (key) => {
                    try {
                        const data = JSON.parse(window.name || '{}');
                        return data[key];
                    } catch (e) {
                        console.error('获取name属性失败:', e);
                        return null;
                    }
                },
                getAll: () => {
                    try {
                        return JSON.parse(window.name || '{}');
                    } catch (e) {
                        console.error('解析name属性失败:', e);
                        return {};
                    }
                }
            };
            
            // 使用示例
            NameManager.set('user', { id: 1, name: '张三' });
            NameManager.set('theme', 'dark');
            const userInfo = NameManager.get('user');
            const allData = NameManager.getAll();
            
            // 恢复原始值
            window.name = originalName;
            
            result.innerHTML = `
                <strong>运行结果：</strong><br>
                用户信息: ${JSON.stringify(userInfo, null, 2)}<br>
                所有数据: ${JSON.stringify(allData, null, 2)}
            `;
            result.style.display = 'block';
        }

        // 页面加载时显示当前name值
        console.log('当前window.name值:', window.name);
    </script>
</body>
</html>
